import math
import numpy as np
import torch
from torch import nn
from d2l import torch as d2l

# 使用三阶多项式来生成训练和测试数据的标签
max_degree = 20  # 多项式的最大阶数
n_train, n_test = 100, 100  # 训练和测试的数据集大小
true_w = np.zeros(max_degree)  # 分配大量空间，np的是一个数组！
true_w[0:4] = np.array([5, 1.2, -3.4, 5.6])  # 设置多项式的系数，即不同阶前的权重

features = np.random.normal(size=(n_train+n_test, 1))  # 生成一个服从正态分布的200行1列的数组
np.random.shuffle(features)  # 随机打乱
# power(x1,x2)，表示对x1求x2次方，数组对应位置分别求，要求列数相同，这里的-1特殊，运算后得到一个200x20的矩阵
poly_features = np.power(features, np.arange(max_degree).reshape(1, -1))
# 对阶数进行处理，将特征从xi调整为 xii! 的原因，这样可以避免很大的i带来的特别大的指数值
for i in range(max_degree):
    poly_features[:, i] /= math.gamma(i+1)  # poly_features[:, i]所有行的列进行除法，math的gamma(n)=(n-1)!、
# labels的维度为（n_train+n_test, ）
labels = np.dot(poly_features, true_w)  # 使用dot点乘实现多项式回归相加起来的形式
labels += np.random.normal(scale=0.1, size=labels.shape)  # 加上一个高斯分布的噪声

# 将np的array类型转换为tensor类，下面可以直接在赋值中使用循环一步实现
true_w, features, poly_features, labels = [torch.tensor(x, dtype=
torch.float32) for x in [true_w, features, poly_features, labels]]
# 检查一下
features[:2], poly_features[:2, :], labels[:2]

# 实现一个函数来评估模型在给定数据集上的损失
def evaluate_loss(net, data_iter, loss):
    mertic = d2l.Accumulator(2)  # 损失总和与样本数量两个系数
    for X, y in data_iter:
        out = net(X)
        y = y.reshape(out.shape)
        l = loss(out, y)
        mertic.add(l.sum(), l.numel())
    return mertic[0] / mertic[1]

# 定义训练函数
# def train(train_features, test_features, train_labels, test_labels, num_epochs = 400):
#     loss = nn.MSELoss(reduction='none')
#     input_shape = train_features.shape[-1]  # 调整模型的输入为特征值的维度
#     # 回归是一个全连接层，不设置偏置，因为我们已经在多项式中实现了它
#     net = nn.Sequential(nn.Linear(input_shape, 1, bias=False))
#     batch_size = min(10, train_labels.shape[0])
#     train_iter = d2l.load_array((train_features, train_labels.reshape(-1, 1)), batch_size)
#     test_iter = d2l.load_array((test_features, test_labels.reshape(-1, 1)), batch_size, is_train=False)
#     trainer = torch.optim.SGD(net.parameters(), lr=0.01)
#     animator = d2l.Animator(xlabel='epoch', ylabel='loss', yscale='log', xlim=[1, num_epochs], ylim=[1e-3, 1e2],legend=['train', 'test'])
#     for epoch in range(num_epochs):
#         d2l.train_ch3(net, train_iter, loss, num_epochs, trainer)
#         if epoch == 0 or (epoch + 1) % 20 == 0:
#             animator.add(epoch + 1, (evaluate_loss(net, train_iter, loss), evaluate_loss(net, test_iter, loss)))
#     print('weight:', net[0].weight.data.numpy())

def train(train_features, test_features, train_labels, test_labels, num_epochs=400):
    loss = nn.MSELoss(reduction='none')
    input_shape = train_features.shape[-1]
    # 不设置偏置，因为我们已经在多项式中实现了它
    net = nn.Sequential(nn.Linear(input_shape, 1, bias=False))
    batch_size = min(10, train_labels.shape[0])
    train_iter = d2l.load_array((train_features, train_labels.reshape(-1,1)), batch_size)
    test_iter = d2l.load_array((test_features, test_labels.reshape(-1,1)), batch_size, is_train=False)
    trainer = torch.optim.SGD(net.parameters(), lr=0.01)
    animator = d2l.Animator(xlabel='epoch', ylabel='loss', yscale='log', xlim=[1, num_epochs], ylim=[1e-3, 1e2], legend=['train', 'test'])
    for epoch in range(num_epochs):
        d2l.train_epoch_ch3(net, train_iter, loss, trainer)
        if epoch == 0 or (epoch + 1) % 20 == 0:
            animator.add(epoch + 1, (evaluate_loss(net, train_iter, loss), evaluate_loss(net, test_iter, loss)))
    print('weight:', net[0].weight.data.numpy())
# 从多项式特征中选择前4个维度，即1,x,x^2/2!,x^3/3!
train(poly_features[:n_train, :4], poly_features[n_train:, :4], labels[:n_train], labels[n_train:])
# 从多项式特征中选择前2个维度，即1和x
train(poly_features[:n_train, :2], poly_features[n_train:, :2], labels[:n_train], labels[n_train:])
# 从多项式特征中选取所有维度
train(poly_features[:n_train, :], poly_features[n_train:, :], labels[:n_train], labels[n_train:], num_epochs=1500)